//
//  NSURLConnectionWithAES128.m
//  AES256
//
//  Created by 杨潇 on 14-4-17.
//
//

#import "NSURLConnectionWithAES128.h"
NSMutableData * _mutableData;
DataBlock _dataBlock;
@implementation NSURLConnection (AES128)
- (void)dealloc
{
    if (_mutableData) {
        _mutableData = nil;
    }
    [super dealloc];
}

+ (id)sendRequestWithHeadStr:(NSString *)head headValue:(NSString *)headValue serviceToken:(NSString *)serviceToken text:(NSDictionary *)textDic dataBlock:(DataBlock)block
{
    _dataBlock = [block copy];
    NSURLConnection * con = [[NSURLConnection alloc] init];
    NSURLConnection * connection = [con sendAsynchronousRequestWithHeadStr:head headValue:headValue serviceToken:serviceToken text:textDic];
    con = nil;
    return connection;
}

- (id)sendAsynchronousRequestWithHeadStr:(NSString *)head headValue:(NSString *)headValue serviceToken:(NSString *)serviceToken text:(NSDictionary *)textDic
{
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:head] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    [request setHTTPMethod:@"POST"];
    if (headValue) {
        [request addValue:headValue forHTTPHeaderField:@"token"];
    }
    if (serviceToken) {
        [request addValue:serviceToken forHTTPHeaderField:@"serviceToken"];
    }
    NSError * error = nil;
    NSData * textData = [NSJSONSerialization dataWithJSONObject:textDic options:0 error:&error];
    if (error) {
        [[YXWindowAlertView sharedWindowAlert] showLableWithTitle:@"字典类型错误！！"];
        return nil;
    }
    NSData * data = [self AES128AndBase64EncodeWithUrlStr:textData key:@"ylife-encryptkey"];
    [request setHTTPBody:data];
    NSURLConnection * connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
    return connection;
}

#pragma mark - NSURLConnectionDataDelegate,NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (!_mutableData) {
        _mutableData = [[NSMutableData alloc] init];
    }
    [_mutableData resetBytesInRange:NSMakeRange(0, _mutableData.length)];
    [_mutableData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_mutableData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%@",[[NSString alloc] initWithData:_mutableData encoding:NSUTF8StringEncoding]);
    NSError * error = nil;
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:_mutableData options:0 error:&error];
    if (!error && dic) {
        _dataBlock(dic);
    }else{
        NSString * dataStr = [[NSString alloc] initWithData:_mutableData encoding:NSUTF8StringEncoding];
        dataStr = [dataStr stringByReplacingOccurrencesOfString:@"\r\n" withString:@"换行符"];
        NSError * dataError = nil;
        NSDictionary * dataDic = [NSJSONSerialization JSONObjectWithData:[dataStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&dataError];
        if (!dataError && dataDic) {
            _dataBlock(dataDic);
        }else{
            [[YXWindowAlertView sharedWindowAlert] showLableWithTitle:@"JSON解析数据失败！！"];
        }
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [[YXWindowAlertView sharedWindowAlert] showLableWithTitle:@"网络异常，请检查你的网络连接！！"];
}

- (NSData *)AES128AndBase64EncodeWithUrlStr:(NSData *)urlData key:(NSString *)key
{
    NSData * aesData = [urlData AES128EncryptWithKey:key];
    NSString * baseStr = [aesData base64EncodedString];
    NSData * bodyData = [baseStr dataUsingEncoding:NSUTF8StringEncoding];
    return bodyData;
}
@end
